package com.yiren.manager.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yiren.core.utils.ResourceUtil;
import com.yiren.manager.domain.TokenResult;

import net.sf.json.JSONObject;

/**
 * @author 颜文豪
 */
public class TokenInterceptor implements HandlerInterceptor {

	@SuppressWarnings("all")
	private void out(HttpServletResponse response, String param) {
		String info = ResourceUtil.getString(param);

		TokenResult result = new TokenResult();
		result.setCode(HTTPStatusCode.Error.value());
		result.setInfo(info);
		result.setToken("");

		JSONObject responseJSONObject = JSONObject.fromObject(result);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(responseJSONObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg) throws Exception {		
		
//		System.out.println("************************");

		
//		System.out.println("************************");
		/*if (request.getParameter("token") == null) {
			this.out(response, "person.account.unentry");
			return false;
		}

		String key = request.getParameter("token").toString();
		TokenForm token = SystemCache.getToken(key);
		if (token == null) {
			this.out(response, "person.account.logout");
			return false;
		}

		Date now = new Date();
		long between = (now.getTime() - token.getCreateTime().getTime()) / 1000;
		if (between > timeout) {
			this.out(response, "person.account.timeout");
			return false;
		}

		token.setCreateTime(new Date());*/
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
